package com.dolphin.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.dolphin.common.dto.TokenResult;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtils {
    //盐
    private static final String SIGN = "pddFDG#@R(*$$";

    private static final String JWT_KEY_PHONE = "passengerPhone";
    private static final String JWT_KEY_IDENTITY = "identity";
    private static final String JWT_KEY_TOKEN_TYPE = "tokenType";

    private static final String JWT_TOKEN_TIME = "tokenTime";


    //生成token
    public static String generatorToken(String phone, String identity, String tokenType) {
        Map<String, String> map = new HashMap<>();

        map.put(JWT_KEY_PHONE, phone);
        map.put(JWT_KEY_IDENTITY, identity);
        map.put(JWT_KEY_TOKEN_TYPE, tokenType);
        // 防止每次生成的token时间一样
        map.put(JWT_TOKEN_TIME, Calendar.getInstance().getTime().toString());

        JWTCreator.Builder builder = JWT.create();
        //整合map
        map.forEach((k, v) -> builder.withClaim(k, v));

        //整合过期时间
//        builder.withExpiresAt(date);

        //生成token
        String token = builder.sign(Algorithm.HMAC256(SIGN));
        return token;


    }

    //解析token
    public static TokenResult parseToken(String token) {
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
        String phone = verify.getClaim(JWT_KEY_PHONE).asString();
        String identity = verify.getClaim(JWT_KEY_IDENTITY).asString();
        TokenResult tokenResult = new TokenResult();
        tokenResult.setPhone(phone);
        tokenResult.setIdentity(identity);
        return tokenResult;

    }

    /**
     * 对解析token异常直接返回null
     *
     * @param token
     * @return
     */
    public static TokenResult checkToken(String token) {
        TokenResult tokenResult = null;
        try {
            tokenResult = parseToken(token);
        } catch (Exception e) {
        }
        return tokenResult;
    }

    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("name", "张三");
        map.put("age", "18");
        String s = generatorToken("18267107437", "1", "accessToken");
        System.out.println(s);
        TokenResult tokenResult = parseToken(s);
        System.out.println(tokenResult.getPhone() + "   " + tokenResult.getIdentity());

    }


    //解析token
}
